@comment -*- Mode: texinfo -*-
@comment This documents the GNU regex library
@setfilename regex

@comment >> @code{"foo"} for literal strings vs @b{"foo"} vs @code{foo}
@comment >>  (this file is presently using the last  --- it looks ok in
@comment >>   info; wait to see what it looks like under botex)


@comment >> superior of (dir) is temporary
@node[top, syntax, , (dir)]

@comment{@defn{regex} regular expression matching and searching library.}
@chapter{`regex' regular expression matching and searching library.}

@section{Overview}

Regular expression matching allows you to test whether a string fits
into a specific syntactic shape.  You can also search a string for a
substring that fits a pattern.

A regular expression describes a set of strings.  The simplest case is
one that describes a particular string; for example, the string @code{foo}
when regarded as a regular expression matches @code{foo} and nothing else.
Nontrivial regular expressions use certain special constructs so that
they can match more than one string.  For example, the regular expression
@code{foo\|bar} matches either the string @code{foo} or the string @code{bar}; the
regular expression @code{c[ad]*r} matches any of the strings @code{cr}, @code{car},
@code{cdr}, @code{caar}, @code{cadddar} and all other such strings with any number of
@code{a}'s and @code{d}'s.

The first step in matching a regular expression is to compile it.
You must supply the pattern string and also a pattern buffer to hold
the compiled result.  That result contains the pattern in an internal
format that is easier to use in matching.

Having compiled a pattern, you can match it against strings.  You can
match the compiled pattern any number of times against different
strings.

@menu
* syntax::	Syntax of regular expressions
* directives::	Meaning of characters as regex string directives.
* emacs::	Additional character directives available
		  only for use within Emacs.
* programming:: Using the regex library from C programs
* unix::	Unix-compatible entry-points to regex library
@end menu

@node [syntax, directives, top, top]

@section{Syntax of Regular Expressions}

Regular expressions have a syntax in which a few characters are special
constructs and the rest are @defn{ordinary}.  An ordinary character is a
simple regular expression which matches that character and nothing else.
The special characters are @code{$}, @code{^}, @code{.}, @code{*}, @code{[}, @code{]} and @code{\}.
Any other character appearing in a regular expression is ordinary,
unless a @code{\} precedes it.@refill

For example, @code{f} is not a special character, so it is ordinary,
and therefore @code{f} is a regular expression that matches the string @code{f}
and no other string.  (It does @i{not} match the string @code{ff}.)  Likewise,
@code{o} is a regular expression that matches only @code{o}.

Any two regular expressions @var{a} and @var{b} can be concatenated.
The result is a regular expression which matches a string if @var{a}
matches some amount of the beginning of that string and @var{b}
matches the rest of the string.

As a simple example, we can concatenate the regular expressions
@code{f} and @code{o} to get the regular expression @code{fo},
which matches only the string @code{fo}.  Still trivial.

Note: for Unix compatibility, special characters are treated as
ordinary ones if they are in contexts where their special meanings
make no sense.  For example, @code{*foo} treats @code{*} as ordinary since
there is no preceding expression on which the @code{*} can act.
It is poor practice to depend on this behaviour; better to quote
the special character anyway, regardless of where is appears.


@node [directives, programming , syntax, top]

@ifinfo
The following are the characters and character sequences which have
special meaning within regular expressions.
Any character not mentioned here is not special; it stands for exactly
itself for the purposes of searching and matching.  @note [syntax]
@end ifinfo

@table 3
@item .
is a special character that matches anything except a newline.
Using concatenation, we can make regular expressions like @code{a.b} which
matches any three-character string which begins with @code{a} and ends with @code{b}.@refill

@item *
is not a construct by itself; it is a suffix, which means the preceding
regular expression is to be repeated as many times as possible.  In @code{fo*},
the @code{*} applies to the @code{o}, so @code{fo*} matches @code{f} followed by any number of @code{o}'s.@refill
The case of zero @code{o}'s is allowed: @code{fo*} does match @code{f}.@refill

@code{*} always applies to the @i{smallest} possible preceding expression.
Thus, @code{fo*} has a repeating @code{o}, not a repeating @code{fo}.@refill

The matcher processes a @code{*} construct by matching, immediately, as many
repetitions as can be found.  Then it continues with the rest of the
pattern.  If that fails, backtracking occurs, discarding some of
the matches of the @code{*}'d construct in case that makes it possible
to match the rest of the pattern.  For example, matching @code{c[ad]*ar}
against the string @code{caddaar}, the @code{[ad]*} first matches @code{addaa},
but this does not allow the next @code{a} in the pattern to match.
So the last of the matches of @code{[ad]} is undone and the following
@code{a} is tried again.  Now it succeeds.@refill

@item +
@code{+} is like @code{*} except that at least one match for the preceding
pattern is required for @code{+}.  Thus, @code{c[ad]+r} does not match
@code{cr} but does match anything else that @code{c[ad]*r} would match.

@item [ ... ]
@code{[} begins a @defn{character set}, which is terminated by a @code{]}.
In the simplest case, the characters between the two form the set.
Thus, @code{[ad]} matches either @code{a} or @code{d},
and @code{[ad]*} matches any string of @code{a}'s and @code{d}'s
(including the empty string), from which it follows that
@code{c[ad]*r} matches @code{car}, etc.@refill

Character ranges can also be included in a character set, by writing two
characters with a @code{-} between them.  Thus, @code{[a-z]} matches
any lower-case letter.  Ranges may be intermixed freely with
individual characters, as in @code{[a-z$%.]}, which matches any
lower case letter or @code{$}, @code{%} or period.@refill

Note that the usual special characters are not special any more inside a
character set.  A completely different set of special characters exists
inside character sets: @code{]}, @code{-} and @code{^}.@refill

To include a @code{]} in a character set, you must make it
the first character.  For example, @code{[]a]} matches @code{]} or @code{a}.
To include a @code{-}, you must use it in a context where it cannot possibly
indicate a range: that is, as the first character, or immediately
after a range.@refill

@item [^ ... ]
@code{[^} begins a @defn{complement character set}, which matches any
character except the ones specified.  Thus, @code{[^a-z0-9A-Z]}
matches all characters @i{except} letters and digits.@refill

@code{^} is not special in a character set unless it is the first character.
The character following the @code{^} is treated as if it were first
(it may be a @code{-} or a @code{]}).@refill

@item ^
is a special character that matches the empty string -- but only
if at the beginning of a line in the text being matched.  Otherwise
it fails to match anything.  Thus, @code{^foo} matches a @code{foo}
which occurs at the beginning of a line.@refill

@item $
is similar to @code{^} but matches only at the end of a line.
Thus, @code{xx*$} matches a string of one or more @code{x}'s
at the end of a line.@refill

@item \
has two functions: it quotes the above special characters
(including @code{\}), and it introduces additional special constructs.@refill

Because @code{\} quotes special characters, @code{\$} is a regular
expression which matches only @code{$}, and @code{\[} is a regular
expression which matches only @code{[}, and so on.@refill

For the most part, @code{\} followed by any character matches only that
character.  However, there are several exceptions: characters which, when
preceded by @code{\}, are special constructs.  Such characters are always
ordinary when encountered on their own.@refill

No new special characters will ever be defined.  All extensions to
the regular expression syntax are made by defining new two-character
constructs that begin with @code{\}.@refill

@item \|
specifies an alternative.
Two regular expressions @var{a} and @var{b} with @code{\|} in
between form an expression that matches anything that either @var{a} or
@var{b} will match.@refill

Thus, @code{foo\|bar} matches either @code{foo} or @code{bar}
but no other string.@refill

@code{\|} applies to the largest possible surrounding expressions.  Only a
surrounding @code{\( ... \)} grouping can limit the grouping power of
@code{\|}.@refill

Full backtracking capability exists when multiple @code{\|}'s are used.@refill

@item \( ... \)
is a grouping construct that serves three purposes:

@enumerate
@item
To enclose a set of @code{\|} alternatives for other operations.
Thus, @code{\(foo\|bar\)x} matches either @code{foox} or @code{barx}.

@item
To enclose a complicated expression for the postfix @code{*} to operate on.
Thus, @code{ba\(na\)*} matches @code{bananana}, etc., with any (zero or
more) number of @code{na}'s.@refill

@item
To mark a matched substring for future reference.

@end enumerate

This last application is not a consequence of the idea of a parenthetical
grouping; it is a separate feature which happens to be assigned as a
second meaning to the same @code{\( ... \)} construct because there is no
conflict in practice between the two meanings.  Here is an explanation
of this feature:@refill

@item \@var{digit}
After the end of a @code{\( ... \)} construct, the matcher remembers the
beginning and end of the text matched by that construct.  Then, later on
in the regular expression, you can use @code{\} followed by @var{digit}
to mean ``match the same text matched the @var{digit}'th time by the
@code{\( ... \)} construct.''@refill

The strings matching the first nine @code{\( ... \)} constructs appearing
in a regular expression are assigned numbers 1 through 9 in order of their
beginnings.
@code{\1} through @code{\9} may be used to refer to the text matched by
the corresponding @code{\( ... \)} construct.@refill

For example, @code{\(.*\)\1} matches any string that is composed of two
identical halves.  The @code{\(.*\)} matches the first half, which may be
anything, but the @code{\1} that follows must match the same exact text.@refill

@end table


There are a number of additional @code{\} regexp directives available for use
within Emacs only.@ifinfo (@note [emacs])
@comment no need to make a tex xref to something one line down!
@end ifinfo
@node [emacs, , directives, top]

@subsection{Constructs Available in Emacs Only}

@table 3
@item \`
matches the empty string, but only if it is at the beginning
of the buffer.@refill

@item \'
matches the empty string, but only if it is at the end of
the buffer.@refill

@item \b
matches the empty string, but only if it is at the beginning or
end of a word.  Thus, @code{\bfoo\b} matches any occurrence of
@code{foo} as a separate word.  @code{\bball\(s\|\)\b} matches
@code{ball} or @code{balls} as a separate word.@refill

@item \B
matches the empty string, provided it is @i{not} at the beginning or
end of a word.@refill

@item \w
matches any word-constituent character.
The editor syntax table determines which characters these are.

@item \W
matches any character that is not a word-constituent.

@item \s@var{code}
matches any character whose syntax is @var{code}.
@var{code} is a letter which represents a syntax code:
thus, @code{w} for word constituent, @code{-} for
whitespace, @code{(} for open-parenthesis, etc.
See the documentation for the Emacs function @code{modify-syntax-entry}
for further details.@refill

Thus, @code{\s(} matches any character with open-parenthesis syntax.

@item \S@var{code}
matches any character whose syntax is not @var{code}.
@end table

@node [programming, compiling, directives, top]

@section{Programming using the @code{regex} library}

@ifinfo
The subnodes accessible from this menu give information on entry
points and data structures which C programs need to interface to the
@code{regex} library.
@end ifinfo

@menu
* compiling::	How to compile regular expressions
* matching::	Frobs which are matched and how
* searching::	Searching for compiled regular expressions
* translation::	Translating characters into other characters
		  (for both compilation and matching)
* registers::	determining what was matched
* split::	matching data which is split into two pieces
* unix::	Unix-compatible entry-points to regex library
@end menu

@node [compiling, matching, programming , programming]

@subsection{Compiling a Regular Expression}

To compile a regular expression, you must supply a pattern buffer.
This is a structure defined, in the include file @code{regex.h}, as follows:
    
@example
struct re_pattern_buffer
  {
    char *buffer   /* Space holding the compiled pattern commands. */
    int allocated  /* Size of space that  buffer  points to */
    int used       /* Length of portion of buffer actually occupied */
    char *fastmap; /* Pointer to fastmap, if any, or zero if none. */
                   /* re_search uses the fastmap, if there is one,
                      to skip quickly over totally implausible
                      characters */
    char *translate;
                   /* Translate table to apply to characters before
                      comparing, or zero for no translation.
                      The translation is applied to a pattern when
                      it is compiled and to data when it is matched. */
    char fastmap_accurate;
                   /* Set to zero when a new pattern is stored,
                      set to one when the fastmap is updated from it. */
  };
@end example

Before compiling a pattern, you must initialize the @code{buffer} field to
point to a block of memory obtained with @code{malloc},
and the @code{allocated} field to the size of that block, in bytes.
The pattern compiler will replace this block with a larger one if necessary.

You must also initialize the @code{translate} field to point to the translate
table that you will use when you match the compiled pattern, or to zero
if you will use no translate table when you match.@xref [translation]

Then call @code{re_compile_pattern} to compile a regular expression
into the buffer:
@example
@code{re_compile_pattern (@var{regex}, @var{regex_size}, @var{buf})}
@end example

@var{regex} is the address of the regular expression (char *),
@var{regex_size} is its length (@code{int}),
@var{buf} is the address of the buffer (@code{struct re_pattern_buffer *}).

@code{re_compile_pattern} returns zero if it succeeds in compiling the regular
expression.  In that case, @code{*buf} now contains the results.
Otherwise, @code{re_compile_pattern} returns a string which serves as
an error message.


@node [matching, searching, compiling, programming]

@subsection{Matching a Compiled Pattern}

Once a regular expression has been compiled into a pattern buffer,
you can match the pattern buffer against a string with @code{re_match}.

@code{re_match (@var{buf}, @var{string}, @var{size}, @var{pos}, @var{regs})}

@var{buf} is, once again, the address of the buffer
        (@code{struct re_pattern_buffer *}).
@var{string} is the string to be matched (@code{char *}).
@var{size} is the length of that string (@code{int}).
@var{pos} is the position within the string at which to begin matching (@code{int}).
        The beginning of the string is position 0.
@var{regs} is described below.  Normally it is zero.@xref[registers]

@code{re_match} returns @code{-1} if the pattern does not match; otherwise,
it returns the length of the portion of @code{string} which was matched.

For example, suppose that @var{buf} points to a buffer containing the result
of compiling @code{x*}, @var{string} points to @code{xxxxxy}, and @var{size} is @code{6}.
Suppose that @var{pos} is @code{2}.  Then the last three @code{x}'s will be matched,
so @code{re_match} will return @code{3}.
If @var{pos} is zero, the value will be @code{5}.
If @var{pos} is @code{5} or @code{6}, the value will be zero, meaning that the null string
was successfully matched.
Note that since @code{x*} matchs the empty string, it will never entirely fail.

It is up to the caller to avoid passing a value of @var{pos} that results in
matching outside the specified string.  @var{pos} must not be negative and
must not be greater than @var{size}.

@node [searching, translation, matching, programming]

@subsection{Searching for a Match}

Searching means trying successive starting positions for a match until a
match is found.

@example
re_search (@var{buf}, @var{string}, @var{size}, @var{startpos}, @var{range}, @var{regs})
@end example

is called like @code{re_match} except that the @var{pos} argument is replaced by
two arguments @var{startpos} and @var{range}.
@code{re_search} tests for a match starting at index @var{startpos}, then at
@code{@var{startpos} + 1}, and so on.  It tries @var{range} consecutive positions
before giving up and returning @code{-1}.
If a match is found, @code{re_search} returns the index at which the match
was found.

If @var{range} is negative, @var{re_search} tries starting positions
@var{startpos}, @code{@var{startpos} - 1}, ... in that order.
@code{|@var{range}|} is the number of tries made.

It is up to the caller to avoid passing value of @var{startpos} and @var{range}
that result in matching outside the specified string.
@var{startpos} must be between zero and @var{size}, inclusive,
and so must @code{@var{startpos} + @var{range} - 1} (if @var{range} is positive)
or @code{@var{startpos} + @var{range} + 1} (if @var{range} is negative).

If you may be searching over a long distance (that is, trying many different
match starting points) with a compiled pattern, you should use a @defn{fastmap}
in it.  This is a block of 256 bytes, whose address is placed in the
@var{fastmap} component of the pattern buffer.
The first time you search for a particular compiled pattern, the fastmap
is set so that @code{@var{fastmap}[@var{ch}]} is nonzero if the character @var{ch} might possibly
start a match for this pattern.
@code{re_search} checks each character against the fastmap so that it can skip
more quickly over non-matches.

If you do not want a fastmap, store zero in the @var{fastmap} component of the
pattern buffer before calling @code{re_search}.  In either case, you must
initialize this component to some reasonable value before you can search.

@node [translation, registers, searching, programming]

@subsection{Translate Tables}

With a translate table, you can apply a transformation to all characters
before they are compared.  For example, a table that maps lower case letters
into upper case (or vice versa) causes differences in case to be ignored
by matching.

A translate table is a block of 256 bytes.  Each character of raw data is
used as an index in the translate table.  The value found there is used
instead of the original character.  Each character in a regular
expression, except for the syntactic constructs, is translated when the
expression is compiled.  Each character of a string being matched is
translated whenever it is compared or tested.

A suitable translate table to ignore differences in case maps all
characters into themselves, except for lower case letters, which are
mapped into the corresponding upper case letters.
It could be initialized by:

@example
for (i = 0; i < 0400; i++)
  table[i] = i;
for (i = 'a'; i <= 'z'; i++)
  table[i] = i - 040;
@end example

You specify the use of a translate table by putting its address in the
@var{translate} component of the compiled pattern buffer.  If this component
is zero, no translation is done.  Since both compilation and matching use
the translate table, you must use the same table contents for both
operations or confusing things will happen.

@node [registers, split, translation, programming]

@subsection{Registers: or ``What Did the @code{\( ... \)} Groupings Actually Match?''}

If you want to find out, after the match, what each of the first nine
@code{\( ... \)} groupings actually matched, you can pass the @var{regs} argument
to the match or search function.  Pass the address of a structure of this type:

@example
struct re_registers
  {
    int start[RE_NREGS];
    int end[RE_NREGS];
  };
@end example

@code{re_match} and {re_search} will store into this structure the data you
want.  @code{@var{regs}->start[@var{reg}]} will be the index in @var{string} of the beginning
of the data matched by the @var{reg}'th @code{\( ... \)} grouping, and
@code{@var{regs}->end[@var{reg}]} will be the index of the end of that data.
Register numbers start at 1 and run to @code{RE_NREGS - 1} (normally @code{9}).
@code{@var{regs}->start[0]} and @code{@var{regs}->end[0]} are similar but describe the
extent of the substring matched by the entire pattern.

Both @code{struct re_registers} and @code{RE_NREGS} are defined in @code{regex.h}.

@node [split, unix, registers, programming]

@subsection{Matching against Split Data}

The functions @code{re_match_2} and @code{re_search_2} allow one to match in or search
data which is divided into two strings.

@code{re_match_2} works like @code{re_match} except that two data strings and
sizes must be given.

@example
re_match_2 (@var{buf}, @var{string1}, @var{size1}, @var{string2}, @var{size2}, @var{pos}, @var{regs})
@end example

The matcher regards the contents of @var{string1} as effectively followed by
the contents of @var{string2}, and matches the combined string against the
pattern in @var{buf}.

@code{re_search_2} is likewise similar to @code{re_search}:

@example
re_search_2 (@var{buf}, @var{string1}, @var{size1}, @var{string2}, @var{size2}, @var{startpos}, @var{range}, @var{regs})

The value returned by @var{re_search_2} is an index into the combined data
made up of @var{string1} and @var{string2}.  It never exceeds @code{@var{size1} + @var{size2}}.
The values returned in the @var{regs} structure (if there is one) are likewise
indices in the combined data.

@node [unix, , split, programming]

@subsection{Unix-Compatible Entry Points}

The standard Unix way to compile a regular expression is to call
@code{re_comp}.  This function takes a single argument, the address of the
regular expression, which is assumed to be terminated by a null character.

@code{re_comp} does not ask you to specify a pattern buffer because it has its
own pattern buffer --- just one.  Using @code{re_comp}, one may match only the
most recently compiled regular expression.

The value of @code{re_comp} is zero for success or else an error message string,
as for @code{re_compile_pattern}.

Calling @code{re_comp} with the null string as argument it has no effect;
the contents of the buffer remain unchanged.

The standard Unix way to match the last regular expression compiled
is to call @code{re_exec}.  This takes a single argument, the address of
the string to be matched.  This string is assumed to be terminated by
a null character.  Matching is tried starting at each position in the
string.  @code{re_exec} returns @code{1} for success or @code{0} for failure.
One cannot find out how long a substring was matched, nor what the
@code{\( ... \)} groupings matched.
